import { UserConfig, ConfigEnv, defineConfig, loadEnv } from 'vite'
import createPlugins from './vite/plugins'
import createCompile from './vite/compile'
import { resolve } from 'path'

// #详细参考: https://cn.vitejs.dev/config/
export default defineConfig(({ mode, command }: ConfigEnv): UserConfig => {
  const viteEnv = loadEnv(mode, __dirname)
  return {
    base: viteEnv.VITE_APP_CONTEXT_PATH,
    resolve: {
      alias: {
        '@': resolve(__dirname, './src')
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    plugins: createPlugins(viteEnv, command === 'build'),
    build: createCompile(mode),
    server: {
      host: '0.0.0.0',
      port: Number(viteEnv.VITE_APP_PORT),
      open: true,
      proxy: {
        [viteEnv.VITE_APP_BASE_URL]: {
          target: viteEnv.VITE_APP_BASE_API,
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(new RegExp('^' + viteEnv.VITE_APP_BASE_URL), '')
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true
        }
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              }
            }
          }
        ]
      }
    },
    // H5 不支持预编译
    // optimizeDeps: {
    //   include: ['vue', 'pinia', '@vueuse/core', 'echarts']
    // }
  }
})
